package zz.note;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 写的常见写法
 *
 * @author Jiaju Zhuang
 */
public class DemoController {

    /**
     * web自定义格式导出
     */
    @GetMapping("/export")
    public void faExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("优惠券信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            List<DemoEntity> list = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                DemoEntity demo = new DemoEntity();
                demo.setCouponNo(String.valueOf(i));
                demo.setCouponName("测试数据");
                demo.setCreateTime(new Date());
            }
            EasyExcel.write(response.getOutputStream(), DemoEntity.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("测试sheet")
                    .doWrite(list);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSONObject.toJSONString(map));
        }
    }

}
